from django.utils import timezone
from apps.articles.models import Article


def expire_article_top_status():
    """检查并处理文章置顶过期"""
    try:
        # 获取当前时间
        now = timezone.now()

        # 查找所有置顶且已过期的文章
        expired_articles = Article.objects.filter(
            top_type=True,
            top_expire_time__isnull=False,
            top_expire_time__lte=now
        )

        expired_count = expired_articles.count()

        if expired_count > 0:
            # 批量更新过期文章
            updated_count = expired_articles.update(
                top_type=False,
                top_expire_time=None
            )

            print(f"Successfully processed {updated_count} expired pinned articles")

            # 输出每篇文章的详细信息
            for article in expired_articles:
                print(f"The article '{article. title}' (ID: {article. acid_id}) has been removed from the top position")
        else:
            print("No expired pinned articles found")

        return expired_count

    except Exception as e:
        print(f"An error occurred while processing the top expiration of the article: {e}")
        return 0


def cleanup_expired_articles():
    """清理过期文章的定时任务入口"""

    print("Start the scheduled task of article cleaning...")

    # 执行置顶过期逻辑
    expired_count = expire_article_top_status()

    # 执行过期自动删除逻辑
    deleted_count = delete_expired_articles()

    print(
        f"The article cleaning task has been completed, processed {expired_count} expired pinned articles, "
        f"and deleted {deleted_count} expired articles"
    )

    return {
        'expired_top_articles': expired_count,
        'deleted_articles': deleted_count,
    }


def delete_expired_articles():
    """删除已到期的文章"""
    try:
        now = timezone.now()

        # 查找所有设置了到期时间且已到期的文章
        expired_articles = Article.objects.filter(
            expire_time__isnull=False,
            expire_time__lte=now
        )

        expired_count = expired_articles.count()

        if expired_count > 0:
            # 批量删除，触发外键级联
            deleted_total, _ = expired_articles.delete()
            print(f"Successfully deleted {expired_count} expired articles (total rows affected: {deleted_total})")
        else:
            print("No expired articles found to delete")

        return expired_count

    except Exception as e:
        print(f"An error occurred while deleting expired articles: {e}")
        return 0
